<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=\, initial-scale=1.0">
    <title>Document</title>
</head>

<body style="display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh">
    <form id="form" novalidate action="">
        <label for="str1">请输入一个字符串:</label>
        <br>
        <input type="text" id="str1" name="str1">
        <br>
        <label for="str2">请输入一个子串:</label>
        <br>
        <input type="text" id="str2" name="str2">
        <input type="submit">
        <br>
        <span>子串出现的次数为</span>
        <span id="result"></span>
        <script>

            document.querySelector('form').addEventListener('submit', e => {
                e.preventDefault()
                const input1 = document.getElementById('str1')
                const input2 = document.getElementById('str2')
                const str1 = input1.value
                const str2 = input2.value
                const count = search(str1, str2);
                var output = document.getElementById('result');
                output.innerHTML = count;

            })
            function search(str1, str2) {
                let count = 0;
                let n = 0;
                n = +str1.indexOf(str2);
                while (n !== -1) {
                    count++;
                    n = str1.indexOf(str2, n + 1);
                }
                return count;
            }

        </script>
</body>

</html>